#include "pagewidget.h"
#include <QLayout>

PageWidget::PageWidget(QWidget *parent, QString pageName) :
    QWidget(parent),
    m_curGadget(0),
    m_pageName(pageName)
{
    m_headViewManager = new ViewManager(this, this);
    setCurrentPlugin(m_headViewManager->view()->getPluginGadget());

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_headViewManager);
}

void PageWidget::split(Qt::Orientation orientation)
{
    m_curViewManager->split(orientation, false);
    m_curViewManager->update();
}

void PageWidget::setCurrentPlugin(IPluginGadget *pluginconfig)
{
    m_curGadget = pluginconfig;
    m_curViewManager = currentViewManager();
    if(m_curViewManager)
        m_curViewManager->update();
    emit currentPluginChanged(pluginconfig);
}

ViewManager * PageWidget::currentViewManager()
{
    if (!m_curGadget) // this is only for startup
        return 0;
    ViewManager *view = m_curGadget ?
                m_headViewManager->findViewManager(m_curGadget) :
                0;
    return view;
}

void PageWidget::closeView(ViewWidget *view)
{
    if (!view)
        return;
    //Find plugin's parent widget.
    ViewManager *viewmanager = m_headViewManager->findViewManager(view);
    //Only one plugin,no need to close it.
    if (viewmanager == m_headViewManager)
        return;
    //Find it's container
    ViewManager *splitter = m_headViewManager->findViewManager(viewmanager);

    splitter->unsplit(viewmanager);
}

void PageWidget::saveSettings(QSettings* qs)
{
    if(!qs)
        return;
    qs->beginGroup("layout");
    m_headViewManager->saveSettings(qs);
    qs->endGroup();
}

void PageWidget::readSettings(QSettings* qs)
{
    qs->beginGroup("layout");
    m_headViewManager->readSettings(qs);
    qs->endGroup();
}
